package com.applcn.shop.aop;

import cn.hutool.core.util.StrUtil;
import com.applcn.core.constants.CommonConstants;
import com.applcn.shop.threadlocal.ShopRequestContext;
import com.applcn.shop.threadlocal.ShopRequestContextHolder;
import com.applcn.user.client.UserClient;
import com.applcn.user.dto.CreateTokenDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * com.applcn.user.aop
 * Description:
 *
 * @author: 大妖怪
 * @date: 2020-01-18 17:15
 */
@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class AspectJ4Jwt {

    private final UserClient userClient;

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) || @within(org.springframework.stereotype.Controller)")
    public void restControllerAspect() {
    }

    @Around("restControllerAspect()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(CommonConstants.TOKEN);
        String shopId = request.getHeader(CommonConstants.SHOP_ID);
        try {
            if (StrUtil.isNotBlank(token)) {
                CreateTokenDTO userInfoDTO = userClient.resolveToken(token);
                if (userInfoDTO != null) {
                    if (userInfoDTO.getUserId() != null) {
                        ShopRequestContextHolder.setUserRequestContext(userInfoDTO.getUserId());
                    }

                    if (userInfoDTO.getMerchantId() != null) {
                        ShopRequestContextHolder.setMerchantRequestContext(userInfoDTO.getMerchantId());
                    }
                }
            }
            if (StrUtil.isNotBlank(shopId)) {
                ShopRequestContextHolder.setUserRequestContext(Long.parseLong(shopId));
            }
            return proceedingJoinPoint.proceed();
        } finally {
            ShopRequestContextHolder.destroyUserRequestContext();
        }
    }
}
